package top.igotcha.consumer.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import top.igotcha.consumer.pojo.User;

/**
 * @author Gotcha
 * @date 2021/1/25
 * @describe
 */
@RestController
@RequestMapping("/consumer")
@Slf4j
//发生熔断时默认的回调函数
@DefaultProperties(defaultFallback = "defaultFallback")
public class ConsumerController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

/*    @GetMapping("{id}")
    public User queryById(@PathVariable Long id){
        String url = "http://localhost:9091/user/" + id;
        return restTemplate.getForObject(url, User.class);
    }*/

    @GetMapping("{id}")
    //发生熔断时的回调函数，当括号内容为空时，使用类中默认的
    @HystrixCommand(fallbackMethod = "queryByIdFallback")
    public String queryById(@PathVariable Long id){
        //获取eureka中注册的user-service实例列表
        //List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("user-service");
        //ServiceInstance serviceInstance = serviceInstanceList.get(0);
        //String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/user/" + id;
        //return restTemplate.getForObject(url, User.class);
        //调用方式，不再手动获取ip和端口，而是直接通过服务名称调用；
        String url = "http://user-service/user/" + id;
        return restTemplate.getForObject(url, User.class).toString();
    }
    public String queryByIdFallback(Long id){
        log.error("查询用户信息失败。id：{}", id);
        return "对不起，网络太拥挤了！";
    }
    public String defaultFallback(){
        return "默认提示：对不起，网络太拥挤了！";
    }

}

